package com.xhy.documents_collection.thread_pool;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhy.documents_collection.cache.UserCache;
import com.xhy.documents_collection.entity.res.OSSRes;
import com.xhy.documents_collection.enums.EmailEnum;
import com.xhy.documents_collection.enums.TimingEnum;
import com.xhy.documents_collection.enums.UploadWayEnum;
import com.xhy.documents_collection.entity.PO.email.EmailSetting;
import com.xhy.documents_collection.entity.PO.task.DownloadRecord;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.entity.PO.task.TaskTimingRecord;
import com.xhy.documents_collection.scheduler.DelayQueueScheduler;
import com.xhy.documents_collection.scheduler.SchedulerHandler;
import com.xhy.documents_collection.service.FileLogService;
import com.xhy.documents_collection.service.task.DownloadRecordService;
import com.xhy.documents_collection.service.EmailSettingService;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.xhy.documents_collection.service.task.TaskTimingRecordService;
import com.xhy.documents_collection.utils.OSSUtil;
import com.xhy.documents_collection.utils.SpringUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2023-03-03 23:27
 * 具体的任务执行器
 * 这个类好像没用了,不用理会
 */
@Deprecated
public class MyRunnable implements Runnable {

    TaskRecordService taskRecordService = SpringUtil.getBean(TaskRecordService.class);

    EmailSettingService emailSettingService = SpringUtil.getBean(EmailSettingService.class);

    TaskTimingRecordService taskTimingRecordService = SpringUtil.getBean(TaskTimingRecordService.class);

    DownloadRecordService downloadRecordService = SpringUtil.getBean(DownloadRecordService.class);


    private TaskTimingRecord taskTimingRecord;

    public MyRunnable() {
    }

    public MyRunnable(
                      TaskTimingRecord taskTimingRecord) {
        this.taskTimingRecord = taskTimingRecord;
    }
    public void setTask(TaskTimingRecord taskTimingRecord){
        this.taskTimingRecord = taskTimingRecord;
    }

    @Override
    public void run() {

        Integer way = taskTimingRecord.getWay();
        if (way == EmailEnum.SUBMIT.type){
            submit();
        }else {
            notice();
        }

    }

    private void submit(){
        Integer taskId = taskTimingRecord.getTaskId();
        // 获取该任务下的所有非空文件并下载
        List<TaskRecord> taskRecords = taskRecordService.list(new LambdaQueryWrapper<TaskRecord>().eq(TaskRecord::getTId, taskId));
        List<String> filePaths = new ArrayList<>();
        long fileSize = 0;
        for (TaskRecord taskRecord : taskRecords) {
            if (!ObjectUtils.isEmpty(taskRecord.getFilePath())){
                filePaths.add(taskRecord.getFilePath());;
                fileSize+=taskRecord.getFileSize();
            }
        }
        Integer userId = taskTimingRecord.getUserId();
        boolean res = true;
        parseContent(taskTimingRecord);
        if (!ObjectUtils.isEmpty(filePaths)){
            // 下载文件到本地并且获取路径
            OSSRes ossRes = OSSUtil.downloadFilesToZipLocal(filePaths);
            String path = ossRes.getPath();
            if (!ossRes.getState()){
                // 获取出错的path
                String message = ossRes.getMessage();
                String errorMsg = " 有出错的文件,文件为:"+message;
                taskTimingRecord.setContent(taskTimingRecord.getContent()+errorMsg);
            }
            // 发送
            res = emailSettingService.sendTaskFile(taskTimingRecord);
            // 修改记录状态
            if (!res){
                taskTimingRecord.setState(TimingEnum.FAILED.type);
                taskTimingRecordService.updateById(taskTimingRecord);
                return;
            }
        }

        // 给自己发送状态邮箱
        EmailSetting emailSetting = emailSettingService.getOne(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId));
        String content = "定时任务:"+taskTimingRecord.getTaskName()+
                "已发送。发送状态:"+(res ? "发送成功。" : "发送失败。") + taskTimingRecord.getContent();
        emailSettingService.send(emailSetting,content);
        taskTimingRecord.setState(TimingEnum.SUCCESS.type);
        taskTimingRecord.setFileSize(fileSize);
        // 添加下载记录
        DownloadRecord downloadRecord = new DownloadRecord();
        downloadRecord.setUserId(userId);
        downloadRecord.setUploadWay(UploadWayEnum.TIMING_UPLOAD.type);
        downloadRecord.setUrl("");
        downloadRecord.setTaskId(taskId);
        downloadRecord.setFileSize(fileSize);
        downloadRecord.setSize(filePaths.size());
        taskTimingRecordService.updateById(taskTimingRecord);
        downloadRecordService.save(downloadRecord);
    }


    private void notice(){
        boolean res = true;
        parseContent(taskTimingRecord);
        res = emailSettingService.sendTaskFile(taskTimingRecord);
        // 修改记录状态
        if (!res){
            taskTimingRecord.setState(TimingEnum.FAILED.type);
            taskTimingRecordService.updateById(taskTimingRecord);
            return;
        }
        taskTimingRecord.setState(TimingEnum.SUCCESS.type);
        taskTimingRecordService.updateById(taskTimingRecord);

    }

    public TaskTimingRecord getTaskTimingRecord() {
        return taskTimingRecord;
    }
    final static String headCount = "headCount";
    final static String practical = "practical";
    final static String noSubmitNames = "noSubmitNames";

    private void parseContent(TaskTimingRecord taskTimingRecord){
        String content = taskTimingRecord.getContent();
        if (!ObjectUtils.isEmpty(content)){
            List<TaskRecord> taskRecordList = taskRecordService.list(new LambdaQueryWrapper<TaskRecord>().eq(TaskRecord::getTId, taskTimingRecord.getTaskId()));
            if (content.contains(headCount)){
                int count = taskRecordList.size();
                // 获取总人数
                content = content.replace(headCount,String.valueOf(count));
            }
            if (content.contains(practical)){
                // 获取已交的人
                long count = taskRecordList.stream().filter(taskRecord -> taskRecord.getIsSubmit()).count();
                content = content.replace(practical,String.valueOf(count));
            }
            if (content.contains(noSubmitNames)){
                // 获取没交的人名字
                List<Integer> userId = taskRecordList.stream().filter(taskRecord -> !taskRecord.getIsSubmit()).map(TaskRecord::getUId).collect(Collectors.toList());
                List<String> names = UserCache.list(userId);
                // 拼接内容
                String newContent = "";
                StringJoiner joiner = new StringJoiner(",");
                for (String name : names) {
                    joiner.add(name);
                }
                newContent+=joiner.toString()+"。";
                content = content.replace(noSubmitNames,newContent);
            }
            content+="。by:该邮件由文件收集平台定时发送。开发者：xhy。";
        }
        taskTimingRecord.setContent(content);
    }
}
